package com.lnj.config;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.ElasticsearchException;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import dev.langchain4j.store.embedding.elasticsearch.ElasticsearchEmbeddingStore;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;

@Configuration
public class ElasticsearchConfig {
    private static final Logger logger = LoggerFactory.getLogger(ElasticsearchConfig.class);


    //创建 RestClient 实例，连接 Elasticsearch
    @Bean
    public RestClient restClient() {
        return RestClient.builder(HttpHost.create("http://localhost:9269")).build();
    }

    @Bean
    public ElasticsearchTransport elasticsearchTransport(RestClient restClient) {
        return new RestClientTransport(restClient, new JacksonJsonpMapper());
    }

    @Bean
    public ElasticsearchClient elasticsearchClient(ElasticsearchTransport transport) {
        return new ElasticsearchClient(transport);
    }

    @Bean
    public ElasticsearchEmbeddingStore elasticsearchEmbeddingStore(ElasticsearchClient client) {
        logger.info("返回 ElasticsearchEmbeddingStore 实例");
        // 构建并返回一个 ElasticsearchEmbeddingStore 对象
        // 这个对象 LangChain4j 可以用来存储和检索向量
        return ElasticsearchEmbeddingStore.builder()
                .serverUrl("http://localhost:9269")  // 设置连接的 Elasticsearch 地址
                .indexName("product_vectors")          // 设置要使用的索引名称
                .dimension(1024)
                .build();
    }
}
